import { Col, Row } from 'antd';
import { connect } from 'dva';
import uuid from 'es6-uuid';
import _ from 'lodash';
import moment from 'moment';
import React, { PureComponent } from 'react';

import { IconC, MapEchartsC, QuickQueryC, SecondHeaderC, TableC } from '@/src/comps';

import styles from './index.less';

class OrganViewC extends PureComponent {
  constructor() {
    super();
    this.state = {
      dataSourceFloat: [],
      dataSourceLeft: [],
      dataSourceRight: [],
      radioVal: 'map',
      defaultArea: '江苏',
      dataList: [
        // {
        //   name: '内蒙古',
        //   range: 1,
        //   totalOrgan: 20,
        //   totalProduct: 129,
        // },
        // {
        //   name: '北京',
        //   range: 2,
        //   totalOrgan: 16,
        //   totalProduct: 346,
        // },
        // {
        //   name: '四川',
        //   range: 3,
        //   totalOrgan: 14,
        //   totalProduct: 110,
        // },
        // {
        //   name: '上海',
        //   range: 4,
        //   totalOrgan: 13,
        //   totalProduct: 134,
        // },
        // {
        //   name: '重庆',
        //   range: 6,
        //   totalOrgan: 6,
        //   totalProduct: 39,
        // },
      ],
    };
  }

  getRightInfo = () => {
    const { dispatch } = this.props;
    const { defaultArea } = this.state;
    dispatch({
      type: 'organProductAnalysisM/getInstitutionOverviewRightInfo',
      payload: {
        province: defaultArea,
        // startDate,
        // endDate,
      },
      callback: (info) => {
        this.setState({
          dataSourceRight: info.sort((a, b) => b?.productNum - a?.productNum),
        });
      },
    });
  };

  getLeftInfo = (nextProps) => {
    const { dispatch } = nextProps;
    dispatch({
      type: 'organProductAnalysisM/getInstitutionOverviewLeftInfo',
      payload: {
        // startDate,
        // endDate,
      },
      callback: (dataSourceLeft) => {
        const dataList = _.cloneDeep(dataSourceLeft);
        // 地图数据标记亮点
        const res = dataList.map((v) => ({ ...v, name: v.province }));
        res.sort((a, b) => b.totalOrgan - a.totalOrgan);
        // 记录最大值 递减赋值size
        let index = res.length;
        // 地图数据，size为散点大小
        // eslint-disable-next-line no-plusplus
        const mapFront = res.map((v, i) => ({ ...v, size: index--, range: i + 1 }));
        // 悬浮map
        dataList.sort((a, b) => b.totalProduct - a.totalProduct);
        // 悬浮table前五数据产品数量前五
        const frontFive = dataList.slice(0, 5);
        // 悬浮地图上的的column
        const floatColumn = frontFive.map((v) => ({
          title: v.province,
          dataIndex: v.province,
          key: v.province,
          width: 80,
          align: 'left',
          render: (text) => text || '--',
        }));
        floatColumn.unshift({
          title: '区域',
          dataIndex: 'area',
          key: 'area',
          width: 140,
          align: 'left',
          className: 'fiveArea',
        });
        // 悬浮的dataSourceFloat
        const dataSourceFloat = [
          {
            area: '累计机构数量',
            areaKey: 'totalOrgan',
          },
          {
            area: '累计产品数量',
            areaKey: 'totalProduct',
          },
          {
            area: '当前规模总量(亿)',
            areaKey: 'totalScale',
          },
        ];
        // eslint-disable-next-line no-unused-vars
        for (const hangDatum of dataSourceFloat) {
          // eslint-disable-next-line no-unused-vars,no-plusplus
          for (let i = 0; i < dataList.length; i++) {
            const dataListNum = dataList[i];
            hangDatum[dataListNum.province] = dataListNum[hangDatum.areaKey];
          }
        }
        this.setState({
          dataSourceLeft: dataSourceLeft.sort((a, b) => b?.totalOrgan - a?.totalOrgan),
          dataList: mapFront, // 设置range排名
          columnsFloat: floatColumn,
          dataSourceFloat,
        });
        this.getRightInfo();
      },
    });
  };

  componentDidMount() {
    this.getLeftInfo(this.props);
  }

  // eslint-disable-next-line react/no-deprecated
  UNSAFE_componentWillReceiveProps(nextProps) {
    const { args, timestamp } = nextProps;
    if (JSON.stringify(args) !== JSON.stringify(this.props.args) || timestamp !== this.props.timestamp) {
      this.getLeftInfo(nextProps);
    }
  }

  onChangeRadio = (radioVal) => {
    this.setState({
      radioVal,
    });
  };

  clickData = (e) => {
    // 点击事件
    const area = e.name;
    this.setState(
      {
        defaultArea: area,
      },
      () => {
        this.getRightInfo();
      },
    );
  };

  rowClick = (record) => {
    this.setState(
      {
        defaultArea: record.province,
      },
      () => {
        this.getRightInfo();
      },
    );
  };

  setRowClass = (record) => (record.province === this.state.defaultArea ? 'table-tr-row-id' : '');

  render() {
    const { dataSourceRight, dataSourceLeft, radioVal, defaultArea, columnsFloat = [], dataSourceFloat } = this.state;
    const {
      loading,
      organProductAnalysisM: { columnsRight, columnsLeft },
    } = this.props;
    return (
      <div className={styles.InstitutionOverview}>
        <SecondHeaderC title='机构总览' />
        <div className={styles.icon}>
          <IconC title={`展示截至到${moment().format('YYYY-MM-DD')}的全租户信息。`} type='info' />
        </div>
        <div className={styles.pa}>
          <div className={styles.modes}>
            <QuickQueryC
              dataSource={[
                { value: 'map', title: '地图模式' },
                { value: 'table', title: '列表模式' },
              ]}
              initialValue={radioVal}
              onChange={(e) => this.onChangeRadio(e)}
            />
          </div>

          <Row gutter={16}>
            <Col span={16}>
              {radioVal === 'map' ? (
                <div>
                  {/* 左侧地图 */}
                  <MapEchartsC
                    dataList={this.state.dataList}
                    click={(e) => this.clickData(e)}
                    //  width='100%'
                    height='800px'
                    defaultName={defaultArea}
                    toolTipFormat={({ data }) => {
                      // 注意Echarts的format}ter接受返回值是字符串 不能用jsx！！！！！！
                      if (data) {
                        return `
                             <div>${data?.name}</div>
                             <div style="display: flex;justify-content: space-between"><span>累计机构数量: &nbsp;</span> <span>${data?.totalOrgan ?? '--'}</span></div>
                             <div style="display: flex;justify-content: space-between"><span>累计产品数量: &nbsp;</span> <span>${data?.totalProduct ?? '--'}</span></div>
                             <div style="display: flex;justify-content: space-between"><span>当前规模总量(亿): &nbsp;</span><span>${data?.totalScale ?? '--'}</span></div>
                            `;
                      }
                      return null;
                    }}
                    toolTipInfo={(info) => {
                      if (info) {
                        return `
                             <div>${info?.name}</div>
                             <div style="display: flex;justify-content: space-between"><span>累计机构数量: &nbsp;</span><span>${info?.totalOrgan ?? '--'}</span></div>
                             <div style="display: flex;justify-content: space-between"><span>累计产品数量: &nbsp;</span><span>${info?.totalProduct ?? '--'}</span></div>
                             <div style="display: flex;justify-content: space-between"><span>当前规模总量(亿): &nbsp;</span><span>${info?.totalScale ?? '--'}</span></div>
                            `;
                      }
                    }}
                  />
                  <div className={styles.floatTable}>
                    {/* 左侧地图浮动列表 */}
                    <TableC
                      columns={columnsFloat || []}
                      loading={loading.effects[`organProductAnalysisM/getInstitutionOverviewLeftInfo`]}
                      dataSource={dataSourceFloat}
                      scroll={{ x: 'max-content' }}
                      rowKey={`id_${uuid(4)}`}
                      hidePage
                      size='small'
                      selfScrollY
                    />
                  </div>
                </div>
              ) : (
                <div>
                  {/* 左侧列表模式 */}
                  <TableC
                    columns={columnsLeft || []}
                    loading={loading.effects[`organProductAnalysisM/getInstitutionOverviewLeftInfo`]}
                    dataSource={dataSourceLeft || []}
                    scroll={{ x: 'max-content', y: 852 }}
                    rowKey={`id_${uuid(4)}`}
                    current={1}
                    pageSize={10}
                    rowClassName={this.setRowClass}
                    onRow={(
                      record, // 表格行点击事件
                    ) =>
                      // eslint-disable-next-line implicit-arrow-linebreak
                      ({
                        onClick: () => {
                          this.rowClick(record);
                        },
                      })
                    }
                    hidePage
                    size='small'
                    selfScrollY
                  />
                </div>
              )}
            </Col>
            <Col span={8}>
              <div className={styles.area}>{defaultArea}</div>
              {/* 右侧列表 */}
              <TableC
                columns={columnsRight || []}
                loading={loading.effects[`organProductAnalysisM/getInstitutionOverviewRightInfo`]}
                dataSource={dataSourceRight || []}
                scroll={{ y: 810 }}
                rowKey={`id_${uuid(4)}`}
                hidePage
                onChange={this.handleTableChange}
                size='small'
                // selfScrollY
              />
            </Col>
          </Row>
        </div>
      </div>
    );
  }
}
export default connect(({ organProductAnalysisM, loading }) => ({
  organProductAnalysisM,
  loading,
}))(OrganViewC);
